package com.xbj.voa.common.utils;

import com.xbj.voa.exception.VoaException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author: 木火
 * @create: 2024-01-11
 * @description:精简返回给客户端的异常信息
 **/
@RestControllerAdvice //是一个组合注解，由@ControllerAdvice、@ResponseBody组成，而@ControllerAdvice继承了@Component，
// 因此@RestControllerAdvice本质上是个Component，用于定义@ExceptionHandler，@InitBinder和@ModelAttribute方法，
// 适用于所有使用@RequestMapping方法
public class CommonExceptionHandler {
    private static Logger LOG = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //可以将某种异常映射为HTTP状态码
    @ExceptionHandler(Exception.class)
    public String exceptionHandle(Exception e){
        LOG.info("执行异常:"+e);
        if(e instanceof MethodArgumentNotValidException){
            //后端数据校验异常 validation
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            String field = exception.getBindingResult().getFieldError().getField();
            String message = exception.getBindingResult().getFieldError().getDefaultMessage();
            return field+message;
        }else if(e instanceof VoaException){
            //自定义异常
            VoaException exception = (VoaException)e;
            return exception.getMsg();
        }else if (e instanceof UnauthorizedException){
            //shiro权限校验异常
            return "您不具备相关权限";
        }else {
            return "后端执行异常";
        }


    }

}
